﻿using GoogleTranslateToken;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Translationassistant
{
    public class GoogleTranslate
    {
        //private static string GoogleTranslateUrl = "https://translate.google.cn/";
        private static string GoogleTranslateAPI = "https://translate.google.cn/m?sl=auto&tl={0}&hl={1}&q={2}";

        /// <summary>
        /// 谷歌翻译
        /// </summary>
        /// <param name="text">待翻译文本</param>
        /// <returns>翻译后文本</returns>
        public static string Translate(string text)
        {
            CookieContainer cc = new CookieContainer();

            string googleTransUrl = string.Format(GoogleTranslateAPI, "en", "zh-CN", HttpUtility.UrlEncode(text));

            //var ResultHtml = GetResultHtml(googleTransUrl, cc, GoogleTranslateUrl);
            var ResultHtml = HttpGet(googleTransUrl);

            string ResultText = "";
            // 匹配 <div class="result-container">laugh</div>
            Regex rs = new Regex("<div class=\"result-container\">(.*?)(?<lan>(.*?))</div>");
            MatchCollection matches = rs.Matches(ResultHtml);
            //遍历所有的img标签对象
            foreach (Match match in matches)
            {
                //获取所有Img的路径src,并保存到数组中
                string MaStr = match.Groups["lan"].Value;
                ResultText = MaStr;
            }

            return ResultText;
        }

        /// <summary>
        /// 数据获取
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            try
            {
                var client = new HttpClient();
                
                var response = client.GetAsync(new Uri(url)).Result;
                string t = response.Content.ReadAsStringAsync().Result;
                return t;
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
